package com.example.springboothibernate.service.impl;

import com.example.springboothibernate.dao.CustomerRepositoryHQL;
import com.example.springboothibernate.dao.UserRepository;
import com.example.springboothibernate.entity.Customer;
import com.example.springboothibernate.entity.User;
import com.example.springboothibernate.service.UserService;
import com.example.springboothibernate.unitls.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;


@Service
public class UserServiceImpl implements UserService {
    private static final Logger logger  = LoggerFactory.getLogger(UserServiceImpl.class);


    @Resource
    private UserRepository userRepository;

    @Resource
    private CustomerRepositoryHQL repositoryHQL;

    @Override
    public Result getByNameAndAge(String name, int age) {
        //根据名字和年龄进行查找
        List<User> list = userRepository.getByNameAndAge(name, age);
        return new Result(list);
    }

    @Override
    public Result queryAll() {
        // List<User> list = userRepository.findAll();
        // return new Result(list);
        //查询全部
        Iterable<User> all = userRepository.findAll();
        return new Result(all);
    }

    @Override
    public Result getById() {
        // User user = userRepository.getById(2);
        // return new Result(user);
        //根据id查找
        Optional<User> byId = userRepository.findById(2);
        logger.info("byId" + byId);
        return new Result(byId);
    }


    public Result addUser(User user){
        //直接保存实体
        User save = userRepository.save(user);
        return new Result(save);       //User{id=5, name='寒冰', age=3}
    }

    @Override
    public Result deleteUser(Integer id) {
        //根据id进行删除
        userRepository.deleteById(id);
        return null;
    }

    @Override
    public Result findAll() {
        //根据id批量查询
        Iterable<User> allById = userRepository.findAllById(Arrays.asList(1, 2, 3));
        System.out.println(allById);
        return new Result(allById);
    }

    @Override
    public Result updateById(User user) {
        //根据id进行添加，有就更新，没有就保存
        // User user = new User();
        // user.setId(2);
        // user.setName("xinde");
        // user.setAge(233);
        User userNew = userRepository.save(user);
        return new Result(userNew);
    }


    public Result save(){
        //内部获取session对象
        List<Customer> all1 = repositoryHQL.findAll1();
        for (Customer customer1 : all1) {
            System.out.println(customer1.toString());
        }
        return new Result(all1);
    }

}
